package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.schedule.IscheduleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.common.dtos.app.ArticleDto;
import com.heima.model.common.dtos.common.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private Tess4jClient tess4jClient;
    @Autowired
    private IscheduleClient scheduleClient;

    /**
     * 自媒体文章审核
     * @param id 自媒体文章id
     */
    @Override
    @Async //标明当前方法是一个异步方法
    public void autoScanWmNews(Integer id) {
        //查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if(wmNews==null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //从内容中提取文本和图片
            Map<String,Object> textAndImage=handleTextAndImage(wmNews);
            //审核文章内容 阿里云接口
            Boolean isTextScan=handleTextScan((String) textAndImage.get("content"),wmNews);
            //如果审核不通过则不向下进行下一步审核,直接退出
            if(!isTextScan){
                return;
            }
            //审核图片 阿里云接口
            Boolean isImageScan=handleImageScan((List<String>)textAndImage.get("images"),wmNews);
            if(!isImageScan){
                return;
            }
            //审核成功后向app端添加文章信息，并向es中同步添加
            AuthPass(wmNews);

        }
    }

    /**
     * 审核成功进行的操作
     * @param wmNews
     */
    public void AuthPass(WmNews wmNews) {
        //审核成功,保存app端相关的文章数据
        ArticleDto articleDto=new ArticleDto();
        //属性拷贝
        BeanUtils.copyProperties(wmNews,articleDto);
        //给不能拷贝的对象逐个赋值
        //文章布局
        articleDto.setLayout(Integer.valueOf(wmNews.getType()));
        //频道名称
        WmChannel wmChannel = wmChannelMapper.selectById(articleDto.getChannelId());
        if(wmChannel!=null) {
            articleDto.setChannelName(wmChannel.getName());
        }
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        //作者id
        articleDto.setAuthorId(wmUser.getApUserId());
        //作者名称
        if(wmUser!=null){
            articleDto.setAuthorName(wmUser.getName());
        }
        //设置文章id
        if(wmNews.getArticleId()!=null){
            articleDto.setId(wmNews.getArticleId());
        }
        articleDto.setCreatedTime(new Date());
        //审核成功后设置状态为上架
        ApArticleConfig apArticleConfig=new ApArticleConfig();
        apArticleConfig.setArticleId(articleDto.getId());
        apArticleConfig.setIsDown(0);
        articleDto.setApArticleConfig(apArticleConfig);
        ResponseResult responseResult = articleClient.saveArticle(articleDto);
        if(!responseResult.getCode().equals(200)){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
        }
        //回填article_id
        wmNews.setArticleId((Long)responseResult.getData());
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setReason("审核成功");
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * TODO:审核图片信息
     * @param images
     * @param wmNews
     * @return
     */
    private Boolean handleImageScan(List<String> images, WmNews wmNews)  {
        boolean flag=true;
        if(CollectionUtils.isEmpty(images)){
            return flag;
        }
        //下载图片minio
        //图片去重
        images= images.stream().distinct().collect(Collectors.toList());
        List<byte[]> bytes=new ArrayList<>();
        try {
            for (String image : images) {
                byte[] byteImage = fileStorageService.downLoadFile(image);

                //对所有提交的图片进行图片识别，识别图中的文字包括敏感词库中的敏感词，则设置不过审
                //图片识别文字审核---begin-----
                //从byte[]转换为butteredImage
                ByteArrayInputStream in = new ByteArrayInputStream(byteImage);
                BufferedImage imageFile = ImageIO.read(in);
                //识别图片的文字
                String result = tess4jClient.doOCR(imageFile);
                //如果图片中的文字包含敏感词,则直接返回不过审
                if(!handleSensitiveScan(result,wmNews)){
                    return false;
                }
                bytes.add(byteImage);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //图片审核
        try{
            //审核失败
            Map map = greenImageScan.imageScan(bytes);
            if(map==null){
                return flag;
            }
            if(map.get("suggestion").equals("block")){
                wmNews.setStatus(WmNews.Status.FAIL.getCode());
                wmNews.setReason("当前图片存在违规内容");
                wmNewsMapper.updateById(wmNews);
            }
            //不确定需要人工审核
            if(map.get("suggestion").equals("review")){
                wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
                wmNews.setReason("当前图片存在疑似违规内容，需要人工审核");
                wmNewsMapper.updateById(wmNews);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 判断文章图片和内容是否包含敏感词
     * @param result
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String result, WmNews wmNews) {
        boolean flag=true;
        //机器审核后对比敏感词库，判断文章是否包含敏感词
        List<String> sensitives=new ArrayList<>();
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(null);
        for (WmSensitive wmSensitive : wmSensitives) {
            sensitives.add(wmSensitive.getSensitives());
        }
        SensitiveWordUtil.initMap(sensitives);
        Map<String, Integer> isSensitive = SensitiveWordUtil.matchWords(result);
        if(isSensitive.size()>0){
            flag=false;
            wmNews.setStatus(WmNews.Status.FAIL.getCode());
            wmNews.setReason("当前文章存在违规内容,内容为:"+isSensitive);
            wmNewsMapper.updateById(wmNews);
        }
        return flag;
    }

    /**
     * TODO:审核文本内容
     * @param content
     * @param wmNews
     * @return
     */
    private Boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag=true;
        if(StringUtils.isBlank(content)){
            return flag;
        }
        try{
            //如果敏感词审核未通过直接返回未过审
            if(!handleSensitiveScan(content, wmNews)){
                return false;
            }
            //审核失败
            Map map = greenTextScan.greeTextScan(content);
            if(map==null){
                return flag;
            }
            if(map.get("suggestion").equals("block")){
                wmNews.setStatus(WmNews.Status.FAIL.getCode());
                wmNews.setReason("当前文章存在违规内容");
                wmNewsMapper.updateById(wmNews);

            }
            //不确定需要人工审核
            if(map.get("suggestion").equals("review")){
                wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
                wmNews.setReason("当前文章存在疑似违规内容，需要人工审核");
                wmNewsMapper.updateById(wmNews);

            }

        }catch (Exception e){
            e.printStackTrace();
        }
            return flag;
    }

    /**
     * 从内容中提取文章和图片,还有封面的图片
     * @param
     * @return
     */
    private Map<String, Object> handleTextAndImage(WmNews wmNews) {

        //存储纯文本内容
        StringBuffer stringBuilders=new StringBuffer();
        stringBuilders.append(wmNews.getTitle());
        //存储图片路径信息
        List<String> images=new ArrayList<>();
        if(StringUtils.isNotBlank(wmNews.getContent())){
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for(Map map:maps){
                if(map.get("type").equals("text")){
                    //文本内容
                    stringBuilders.append(map.get("value"));
                }
                if(map.get("type").equals("image")){
                    //图片内容
                    images.add((String) map.get("value"));
                }
            }
            //提取文章中的封面图片
            if(StringUtils.isNotBlank(wmNews.getImages())){
                String[] split = wmNews.getImages().split(",");
                images.addAll(Arrays.asList(split));
            }
        }
        Map<String,Object> map=new HashMap<>();
        map.put("content",stringBuilders.toString());
        map.put("images",images);
        return map;
    }
}
